package com.hzpd.hainan.module.news.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.App;
import com.hzpd.hainan.app.ToolBarActivity;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.custorm.ListViewInScrollView;
import com.hzpd.hainan.custorm.NumberProgressBar;
import com.hzpd.hainan.custorm.VideoEnabledWebChromeClient;
import com.hzpd.hainan.model.base.BaseEntity;
import com.hzpd.hainan.model.event.LoginSuccessEvent;
import com.hzpd.hainan.model.news.CommenEntity;
import com.hzpd.hainan.model.news.CommentBean;
import com.hzpd.hainan.model.news.IsCollectionEntity;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.news.NewsDetailBean;
import com.hzpd.hainan.model.news.NewsDetailEntity;
import com.hzpd.hainan.model.usercenter.EmptyEntity;
import com.hzpd.hainan.model.usercenter.EmptyEntityList;
import com.hzpd.hainan.module.news.adapter.CommentAdapter;
import com.hzpd.hainan.module.news.adapter.ListDataSetObserver;
import com.hzpd.hainan.module.news.dialog.InputPop;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.DeviceUtils;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.MyJavascriptInterface;
import com.hzpd.hainan.utils.NetWorkHelper;
import com.hzpd.hainan.utils.PageCtrl;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.StringUtils;
import com.hzpd.hainan.utils.TUtils;
import com.hzpd.hainan.wxapi.SharedUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.hzpd.hainan.R.id.newdetail_comm_listview;


/**
 * Created by 猪猪侠 on 2017/7/4.
 */

public class NewsHtmlDetailActivity extends ToolBarActivity {

    @BindView(R.id.newsdetails_wv_pb)
    NumberProgressBar newsdetailsWvPb;//进度条
    @BindView(R.id.xf_newshtmldetail_wv_detail)
    WebView xfNewshtmldetailWvDetail;//webview
    @BindView(newdetail_comm_listview)
    ListViewInScrollView newdetailCommListview;//评论列表
    @BindView(R.id.comments_news_ll)
    LinearLayout commentsNewsLl;//评论根布局
    @BindView(R.id.news_detail_sv)
    PullToRefreshScrollView newsDetailSv;//最外层滑动布局
    @BindView(R.id.news_detail_bak)
    LinearLayout newsDetailBak;//返回按钮
    @BindView(R.id.et_pinglun_id)
    EditText etPinglunId;//评论输入框
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;//跟帖数
    @BindView(R.id.newdetail_comments)
    RelativeLayout newdetailComments;//眼镜按钮
    @BindView(R.id.xf_newshtmldetail_iv_collection)
    ImageView xfNewshtmldetailIvCollection;//收藏 图标
    @BindView(R.id.rl_newdetail_collection)
    RelativeLayout rlNewdetailCollection;//收藏 布局
    @BindView(R.id.newdetail_share)
    RelativeLayout newdetailShare;//分享图标
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout newsDetailLlBottom1;//分享布局
    @BindView(R.id.root_ll)
    RelativeLayout rootLl;//根布局
    @BindView(R.id.xf_newshtmldetail_nonVideoLayout)
    LinearLayout xfNewshtmldetailNonVideoLayout;
    @BindView(R.id.xf_newshtmldetail_videoLayout)
    FrameLayout xfNewshtmldetailVideoLayout;
    @BindView(R.id.tv_url)
    TextView tv_url;
    @BindView(R.id.tv_title)
    TextView tv_title;

    private View xf_newshtmldetail_videoLoading;
    private NewsBean nb;
    private String from;
    private VideoEnabledWebChromeClient webChromeClient;
    private NewsDetailBean ndb;
    private String URL;
    private final int  PAGE_SIZE = 15;
    private int page = 1;
    private InputPop inputPop;
    private CommentAdapter commAdapter;
    boolean isClear = true;
    String tid;

    String isfavourite;
    @Override
    public String initToolBarTitle() {
        return null;
    }

    @Override
    public int setMyContentView() {
        return R.layout.newshtmldetails_layout;
    }

    @Override
    public void initView() {
        setMainTitle();
        if("47".equals(spu.getLanguage())){
            setLogo(false);
        }else{
            setLogo(true);
        }
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        tid=intent.getStringExtra("tid");
        try {
            from = intent.getStringExtra("from");
        } catch (Exception e) {
            from = null;
        }
        nb = (NewsBean) intent.getSerializableExtra("newbean");
        if(spu.getLanguage().equals(CODE.ZHONGWEN)){
            tv_title.setText("守望相助");
        }else {
            tv_title.setText("སོ་ལྟའི་རོགས་སྐྱོར།");
        }
        setWebView();
    }

    private void setWebView() {
        WebSettings webSettings = xfNewshtmldetailWvDetail.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(App.getInstance().getAllDiskCacheDir());
        xfNewshtmldetailWvDetail.setHorizontalScrollBarEnabled(false);//水平不显示
        xfNewshtmldetailWvDetail.setVerticalScrollBarEnabled(false); //垂直不显示
        if (NetWorkHelper.isNetConnected(activity)) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webSettings.setAllowFileAccess(true);

        MyJavascriptInterface jsInterface=new MyJavascriptInterface(activity,ndb);
        // 添加js交互接口类，并起别名 imagelistner
        xfNewshtmldetailWvDetail.addJavascriptInterface(this, "imagelistner");
        xfNewshtmldetailWvDetail.addJavascriptInterface(this, "shareWeb");
        xfNewshtmldetailWvDetail.addJavascriptInterface(this, "loginWeb");
        //字号
        //TODO
        int textSize = spu.getTextSize();
        LogUtils.i("textsize-->"+textSize);
        setWebViewTextSize(textSize);
        xf_newshtmldetail_videoLoading = activity.getLayoutInflater().inflate(R.layout.xf_view_loading_video, null);
        newsDetailSv.setMode(PullToRefreshBase.Mode.DISABLED);
        xfNewshtmldetailWvDetail.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                xfNewshtmldetailWvDetail.loadUrl("javascript:getimg()");
                xfNewshtmldetailWvDetail
                        .loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
                getCommentList();
                view.loadUrl("javascript:setImageEvent()");//设置网页中所有图片监听
            }
        });
//        xfNewshtmldetailWvDetail.setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                super.onProgressChanged(view, newProgress);
//                newsdetailsWvPb.setVisibility(View.VISIBLE);
//                newsdetailsWvPb.setProgress(newProgress);
//                if (newProgress > 95) {
//                    newsdetailsWvPb.setVisibility(View.GONE);
//                }
//            }
//        });

        getNewsDetails();
        isCollection();
        commAdapter  = new CommentAdapter(activity,0);
        commAdapter.registerDataSetObserver(new ListDataSetObserver(newdetailCommListview));
        newdetailCommListview.setAdapter(commAdapter);
        newdetailCommListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (!"0".equals(ndb.getComflag())) {
                    CommentBean cb = (CommentBean) commAdapter.getItem(position);
                    popCommentActivity(cb);
                }
            }
        });
    }
    private void setWebViewTextSize(int textSize) {
        LogUtils.e("setWebViewTextSize 字体-->2" + textSize);
        WebSettings settings = xfNewshtmldetailWvDetail.getSettings();
        WebSettings.TextSize t = null;
        switch (textSize) {
            case CODE.textSize_big:
                //xf_newshtmldetail_wv_detail.loadUrl("javascript:changeFontSize(3)");
                settings.setTextZoom(115);
                break;
            case CODE.textSize_normal:
                //xf_newshtmldetail_wv_detail.loadUrl("javascript:changeFontSize(2)");
                settings.setTextZoom(100);
                break;
            case CODE.textSize_small:
                //xf_newshtmldetail_wv_detail.loadUrl("javascript:changeFontSize(1)");
                settings.setTextZoom(80);
                break;
            default:
                //xf_newshtmldetail_wv_detail.loadUrl("javascript:changeFontSize(18)");
                settings.setTextZoom(100);
                break;
        }
        xfNewshtmldetailWvDetail
                .loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
    }

    /**
     * 获取新闻
     */
    private void getNewsDetails() {
        LogUtils.i("nid-->"+nb.getNid());
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        Factory.provideHttpService()
                .newsDetail(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsDetailEntity entity) {
                        LogUtils.i("detail-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsDetailEntity>() {
                    @Override
                    public void call(NewsDetailEntity entity) {
                        ndb = entity.data;
                        addVisits();
                        isfavourite=entity.data.getIsfavorite();
                        setNewsData(entity.data.getIsfavorite());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("detail-->throwable-->"+throwable);
                    }
                });
    }

    // 设置新闻详情
    private void setNewsData(String isfavoriteid) {
        if (null == ndb) {
            return;
        }
        String url = ndb.getNewsurl();
        if (ndb.getVoteflag() != null && ndb.getVoteflag().equals("1")){
            if (!StringUtils.isEmpty(ndb.getNewsurl())){
                if (null==spu.getUser()){
                    URL = InterfaceJsonfile.BASEURL + nb.getNid()+"/uid//device/"+ DeviceUtils.getIMEI(this)+"&isfavoriteid="+isfavoriteid;
                }else {
                    URL = InterfaceJsonfile.BASEURL + nb.getNid()+"/uid/"+spu.getUser().getUid()+"/device/"+ DeviceUtils.getIMEI(this)+"&isfavoriteid="+isfavoriteid;
                }
            }
        }else{
            if (!StringUtils.isEmpty(nb.getNewsurl())){

                if (null==spu.getUser()){
                    URL = url + "?nid="+nb.getNid()+"&uid=&math="+Math.random()+"&device="+ DeviceUtils.getIMEI(this)+"&isfavoriteid="+isfavoriteid;
//                    URL = url + "?nid="+nb.getNid()+"&uid="+ DeviceUtils.getIMEI(this)+"&math="+Math.random()+"&device="+ DeviceUtils.getIMEI(this);
                }else {
                    URL = url + "?uid="+spu.getUser().getUid()+"&nid="+nb.getNid()+"&math="+Math.random()+"&device="+ DeviceUtils.getIMEI(this)+"&isfavoriteid="+isfavoriteid;
                }
            }
        }
        if (StringUtils.isEmpty(URL)){
            URL=url;
        }
        LogUtils.e("url-3->" + URL);
        tv_url.setText(URL);
        xfNewshtmldetailWvDetail.loadUrl(URL);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.news_detail_bak, R.id.et_pinglun_id, R.id.rl_newdetail_collection, R.id.newdetail_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.news_detail_bak:
                activity.onBackPressed();
                break;
            case R.id.et_pinglun_id:
                if (spu.getUser()!=null){
                    popCommentActivity(null);
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }

                break;
            case R.id.rl_newdetail_collection:
                if (spu.getUser()!=null){
                    addCollection();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }

                break;
            case R.id.newdetail_share:
                String imgurl = null;
                if (null != ndb.getImgs() && ndb.getImgs().size()> 0) {
                    imgurl = ndb.getImgs().get(0);
                }
                SharedUtil.showShares(true, null, ndb.getTitle(), InterfaceJsonfile.BASEURL + ndb.getNid(), imgurl, activity);
                break;
        }
    }







    //评论弹窗
    private void popCommentActivity(final CommentBean commentBean){
        if (null == ndb) {
            return;
        }
        if (!"0".equals(ndb.getComflag())) {
            if (inputPop == null){
                inputPop = new InputPop(activity, new InputPop.InputListener() {
                    @Override
                    public void inputstr(String string) {
                        if (commentBean != null) {
                            sendComment(string, commentBean.getCid());
                        }else {
                            sendComment(string, null);
                        }
                    }
                });
            }
            inputPop.setFocusable(true);
            inputPop.showAtLocation(findViewById(R.id.root_ll), Gravity.BOTTOM,0,0);
        } else {
            TUtils.toast("该条新闻不可评论");
        }
    }
    public  void addVisits(){
        Map<String,String> map=new HashMap<>();
        map.put("nid",nb.getNid());
        map.put("type","1");
        map.put("siteid",InterfaceJsonfile.SITEID);
        map.put("num","1");
        map.put("tid",tid);
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }

        map.put("device",DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                       LogUtils.i("emptyEntityList----"+emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }



    //发表评论接口
    private void sendComment(String content,String cid){
        showDialog();
            Map<String, String> map = new HashMap<>();
            map.put("nid", nb.getNid());
            map.put("uid", spu.getUser().getUid());
            map.put("type", "1");
            map.put("content", content);
            map.put("cid", cid);
            map.put("siteid", InterfaceJsonfile.SITEID);
            Factory.provideHttpService()
                    .newsComment(ParamUtils.getRequestParam(map))
                    .onBackpressureBuffer()
                    .subscribeOn(Schedulers.io())
                    .filter(new Func1<BaseEntity, Boolean>() {
                        @Override
                        public Boolean call(BaseEntity entity) {
                            LogUtils.i("200-->" + entity.code);
                            if ("200".equals(entity.code)) {
                                LogUtils.i("200-->成功");
                                return true;
                            }
                            LogUtils.i("200失败");
                            return false;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<BaseEntity>() {
                        @Override
                        public void call(BaseEntity entity) {
                            disMissDialog();
                            if ("200".equals(entity.code)){
                                TUtils.toast("评论成功");
                                etPinglunId.setText("");
                            }else{
                                TUtils.toast(entity.msg);
                            }
//                            setData();
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            TUtils.toast("评论失败");
                            disMissDialog();
                        }
                    });
    }
    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser()==null){
            return;
        }
        map.put("typeid", nb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_collection);

                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", nb.getNid());
        map.put("uid",spu.getUser().getUid());
        map.put("type", "1");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                TUtils.toast("收藏成功");
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_collection);
                            } else {
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_nd_collection);
                                TUtils.toast("收藏取消");
                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    //获取评论列表
    private void getCommentList(){
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        map.put("type", "1");
        map.put("Page", page+"");
        map.put("PageSize", PAGE_SIZE+"");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsCommentList(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommenEntity, Boolean>() {
                    @Override
                    public Boolean call(CommenEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommenEntity>() {
                    @Override
                    public void call(CommenEntity entity) {
                        if ("200".equals(entity.code)){
                            commentsNewsLl.setVisibility(View.VISIBLE);
                            newdetailCommListview.setVisibility(View.VISIBLE);
                            commAdapter.appendData(entity.data, isClear);
                            commAdapter.notifyDataSetChanged();
                            //------+
                            //----
                            if (entity.data.size() < PAGE_SIZE) {
                                newsDetailSv.setMode(PullToRefreshBase.Mode.DISABLED);
                            } else {
                                newsDetailSv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                            }

                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }


    @JavascriptInterface
    public void openImages(String curentImg, String allImg){

        int position = 0;
        String[] temp = null;
        ArrayList<String> list = new ArrayList<>();
        temp = allImg.split(",");
        for (int i = 0;i<temp.length;i++){
            String img = temp[i];
            LogUtils.e("img-->"+img);
            list.add(img);
            if (img.equals(curentImg)){
                position = i;
            }
        }
        Intent intent = new Intent();
        intent.putExtra("from", "news");
        intent.putExtra("position", position);
        intent.putStringArrayListExtra("imags",list);
        //intent.putExtra("imags",temp);
        intent.putExtra("ndb", ndb);
        intent.setClass(this, NewsAlbumActivity.class);
        startActivity(intent);
    }


    @JavascriptInterface
    public void loginAndroid(){
        if (spu.getUser()!=null){
            addCollection();
        }else{
            PageCtrl.start2LoginActivity(activity);
        }
    }

    @JavascriptInterface
    public void showAndroid(){
        String imgurl = null;
        if (null != ndb.getImgs() && ndb.getImgs().size()> 0) {
            imgurl = ndb.getImgs().get(0);
        }
        SharedUtil.showShares(true, null, ndb.getTitle(), InterfaceJsonfile.BASEURL + ndb.getNid(), imgurl, activity);
    }

    @Subscribe
    public void onEventMainThread(LoginSuccessEvent csl) {
        LogUtils.i("csl----------------" + csl.isIslogin());
        String url=null;
        if (csl.isIslogin()) {

            url = url + "?uid="+spu.getUser().getUid()+"&nid="+nb.getNid()+"&math="+Math.random()+"&device="+ DeviceUtils.getIMEI(this)+"&isfavoriteid="+isfavourite;


            xfNewshtmldetailWvDetail.loadUrl(url);
        }
    }
}
